/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sack.yahoo.ym;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import ymsg.network.AccountLockedException;
import ymsg.network.LoginRefusedException;
import ymsg.network.Session;
import ymsg.network.YahooGroup;
import ymsg.network.YahooUser;
import ymsg.network.StatusConstants;


    
/**
 * Top component which displays something.
 */
final class YMwindowTopComponent extends TopComponent {

    private static YMwindowTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";

private int invisible=1;
    private static final String PREFERRED_ID = "YMwindowTopComponent";
    private boolean connectionClosed;
    private boolean loggedIn;
    Session yahooMessengerSession;
     MySessionListener mySessionListener;
    private String recipient;
    
    
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private DefaultListModel listModel;
    private JButton jLogoutButton;
    
    
    private YMwindowTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(YMwindowTopComponent.class, "CTL_YMwindowTopComponent"));
        setToolTipText(NbBundle.getMessage(YMwindowTopComponent.class, "HINT_YMwindowTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }


    private void frndlistwin(JList jList1) {
        jPanel1.setVisible(false);
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jLogoutButton=new javax.swing.JButton(); 
        final JList recep=jList1;
         jPanel2.setBackground(new java.awt.Color(240, 240, 240));
        
        jList1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jList1.setFont(new java.awt.Font("MS Reference Sans Serif", 0, 14));
       jList1.setForeground(new java.awt.Color(255, 0, 0));
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jList1);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
               recipient=(String)recep.getSelectedValue();
              
               int n=recipient.indexOf(" ");
  recipient=recipient.substring(0,n);
  System.out.println(recipient);
            
            }
        });
        
        
        
        jLogoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jLogoutButtonActionPerformed(evt);
            }

            private void jLogoutButtonActionPerformed(ActionEvent evt) {
               logout();
            }
        });
        
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }

            private void jList1MouseClicked(MouseEvent evt) {
               if(evt.getClickCount()==2)
               {
                   System.out.println("entered event");
                  
                   UserWindow uw=  new UserWindow(recipient,yahooMessengerSession,mySessionListener);
                   mySessionListener.SetUserWindow(uw);
               }
            }
        });

        
          org.openide.awt.Mnemonics.setLocalizedText(jLogoutButton, "Logout");
        jLogoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jLogoutButtonActionPerformed(evt);
            }

            private void jLogoutButtonActionPerformed(ActionEvent evt) {
                logout();
            }
        });
    
       
        
        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                .addContainerGap()
                  .add(20,20, 20)
                  .add(jLogoutButton))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(66, 66, 66)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 392, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(jLogoutButton)
                .add(44, 44, 44))
                
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
     
  
        
        
        
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        Jname = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        Signin = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        jCheckBox1 = new javax.swing.JCheckBox();

        jPanel1.setBackground(new java.awt.Color(240, 240, 240));

        Jname.setColumns(10);
        Jname.setFont(new java.awt.Font("MS Reference Sans Serif", 0, 12));
        Jname.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JnameActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Login ID!");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Password");

        org.openide.awt.Mnemonics.setLocalizedText(Signin, "Sign in");
        Signin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SigninActionPerformed(evt);
            }
        });

        jPasswordField1.setColumns(15);
        jPasswordField1.setFont(new java.awt.Font("MS Reference Sans Serif", 0, 10));

        jCheckBox1.setBackground(new java.awt.Color(240, 240, 240));
        org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, "Sign in as invisible to everyone");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(104, 104, 104)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 56, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(97, 97, 97)
                        .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(44, 44, 44)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jCheckBox1)
                            .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(Jname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 171, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(95, 95, 95)
                        .add(Signin)))
                .addContainerGap(66, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(180, 180, 180)
                .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(Jname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(39, 39, 39)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(28, 28, 28)
                .add(jCheckBox1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 60, Short.MAX_VALUE)
                .add(Signin)
                .add(44, 44, 44))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void JnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JnameActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_JnameActionPerformed

    private void SigninActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SigninActionPerformed
        // TODO add your handling code here:
        login();
    }//GEN-LAST:event_SigninActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
        invisible=0;
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Jname;
    private javax.swing.JButton Signin;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized YMwindowTopComponent getDefault() {
        if (instance == null) {
            instance = new YMwindowTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the YMwindowTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized YMwindowTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(YMwindowTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof YMwindowTopComponent) {
            return (YMwindowTopComponent) win;
        }
        Logger.getLogger(YMwindowTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
    // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
    // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return YMwindowTopComponent.getDefault();
        }
    }
    
    
    
    
    
    
    
    
    
    
    public void login() {
        try {

            yahooMessengerSession = new Session();
            mySessionListener = new MySessionListener(this);
            yahooMessengerSession.addSessionListener(mySessionListener);
            if (this.invisible == 0) {
                yahooMessengerSession.setStatus(StatusConstants.STATUS_INVISIBLE);
            }
            String userName = Jname.getText();
            String password = jPasswordField1.getText();

            if ((userName.equals("")) || (password.equals(""))) {
                System.out.println("User name/password is blank");
            } else {
                try {
                    System.out.println("Attempting login");
                    yahooMessengerSession.login(userName, password);
                    System.out.println("Username: " + userName);
                    System.out.println("Password: " + password);
                    System.out.println("ConnectionClosed" + connectionClosed);
                    this.frndlistcreator();
                } catch (IllegalStateException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (AccountLockedException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (LoginRefusedException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        } catch (IllegalArgumentException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }

			
		
		
	

	}
    
    
    private void frndlistcreator(){
      
        String status=null;
       YahooGroup[] yg = yahooMessengerSession.getGroups();
       
      listModel = new DefaultListModel();
	for(int i=0;i<yg.length;i++)
	{   System.out.println(yg[i].getName());
              for(int j=0;j<yg[i].getMembers().size();j++)
	    {   YahooUser yu = (YahooUser) yg[i].getMembers().get(j);
	      
                if(yu.isLoggedIn())
                   status=" - Online";
               
                else
                    status=" ";
             
                listModel.addElement(yu.getId()+status);
                                
	    }
	}
     JList frndlist = new JList(listModel);
     frndlistwin(frndlist);
    }


    public void logout() {
		try {
			yahooMessengerSession.logout();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//getMessageHistoryTextArea().setText("");
		loggedIn = false;
		connectionClosed = false;
		//setUnviewable();

	}


}  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

